using System.Collections.Generic;
using Godot;

public class CopperFluidPipeBlock : BlockMaterial
{
    public CopperFluidPipeBlock() : base("copper_fluid_pipe")
    {
        SetCollide(false);
        SetDisplayName("铜制流体管道");
        SetStateMax(16);
        SetBlockEntityCreate(() => new CopperFluidPipeEntity());
        SetTickEvent(Tick);
    }
    public void Tick(UpdataTickEvent e)
    {
        const int speed = 10;
        bool IsTarget(int x, int y)
        {
            BlockData block = e.world.GetBlock(e.Position + new Vector3I(x, y));
            return block != null && (block.GetFluid("steam") != null);
        }
        e.block.SetState(e.GetAngle<BlockEntity>());
        CopperFluidPipeEntity blockentity = (CopperFluidPipeEntity)e.block.blockEntity;
        if (blockentity.steam.amount <= 0)
        {
            blockentity.steam.amount = 0;
            return;
        }
        List<BlockData> round = new List<BlockData>();
        if (IsTarget(1, 0)) round.Add(e.world.GetBlock(e.Position + new Vector3I(1, 0)));
        if (IsTarget(0, 1)) round.Add(e.world.GetBlock(e.Position + new Vector3I(0, 1)));
        if (IsTarget(-1, 0)) round.Add(e.world.GetBlock(e.Position + new Vector3I(-1, 0)));
        if (IsTarget(0, -1)) round.Add(e.world.GetBlock(e.Position + new Vector3I(0, -1)));
        for (int i = 0; i < round.Count; i++)
        {
            BlockData block = round[i];
            FluidData fd = block.GetFluid("steam");
            if (fd.GetLastAmount() > blockentity.steam.GetLastAmount())
            {
                if (fd.AddAmount(speed))
                {
                    blockentity.steam.amount -= speed;
                }
            }
        }
    }
}